//////////////////////////////////////////////////////
// Read data file and search for patterns that match
// player's previous 4 moves
//
// Evaluate probability of rock, paper, scissors for
// the 5th move, and play the move that beats the most
// likely choice
//
// Need to add:
// 1. ability to append current game data 
//    to file
// 2. Track computer move data
// 3. Compare patterns and modify probabilities
//    for computer sequences that win more
//////////////////////////////////////////////////////

#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

#include "rpsrandom.h"

int randomRPS();

std::pair<int, double> trainRPS(std::string pattern, int length){
	//////////////////////////////////////////////////////
	// Read training data
	//////////////////////////////////////////////////////
	std::string data;
	std::ifstream myfile ("movehistory.txt");
	
	if(myfile){
		while(!myfile.eof()){
			data.push_back(myfile.get());
		}
	}
	
	//////////////////////////////////////////////////////
	// Search data file for matching patterns
	//////////////////////////////////////////////////////
	std::vector<int> positions;
	
	for(int i=0; i<(data.size()-(length+1)); i++){
		if(data.substr(i,length)==pattern){
			positions.push_back(i);
		}
	}
		
	double rock=0;
	double paper=0;
	double scissors=0;

	for(int i=0; i<positions.size(); i++){
		int next=positions[i]+length;
		if(data[next]=='R') rock++;
		if(data[next]=='P') paper++;
		if(data[next]=='S') scissors++;
	}
	
	// std::cout << std::endl;
	// std::cout << "looking for pattern: " << pattern << std::endl;
	// std::cout << "pattern found " << positions.size() << " times" << std::endl;
	
	
	//////////////////////////////////////////////////////
	// Create vector of move probabilities
	//////////////////////////////////////////////////////
	std::vector<double> props;
	props.resize(3);
	
	if(positions.size()!=0){
		props[0]=rock/(double)positions.size();
		props[1]=paper/(double)positions.size();
		props[2]=scissors/(double)positions.size();
	} else {
		props[0]=0;
		props[1]=0;
		props[2]=0;
	}
	//Print move probabilities
	// for(int i=0; i < props.size(); ++i) {
        // std::cout << " " << props[i];
    // }
    // std::cout << std::endl;
	
	//////////////////////////////////////////////////////
	//Find best guess and determine move that beats it
	//////////////////////////////////////////////////////
	int bestguess=std::distance(props.begin(), std::max_element(props.begin(), props.end()));
	int move=(bestguess+1)%3;

	myfile.close();
	
	//////////////////////////////////////////////////////
	// return computer move and probability that the 
	// outcome occurs
	//////////////////////////////////////////////////////
	std::pair<int, double> move_prob;
	move_prob=std::make_pair(move, props[bestguess]);
	return move_prob;
}
